//
//  LoginViewController.m
//  FZAH
//
//  Created by 潇湘妃子 on 17/2/17.
//  Copyright © 2017年 zdqk. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
//#import "ForgetPassViewController.h"
#import "NSObject+Object.h"

@interface LoginViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phoneNum;
@property (weak, nonatomic) IBOutlet UITextField *passwd;
@property (weak, nonatomic) IBOutlet UIButton *passwdButton;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIView *phoneNumBackView;
@property (weak, nonatomic) IBOutlet UIView *passWordBackView;

//@property (nonatomic, strong) void (^authOpFinish)(void);
//@property (nonatomic, strong) void (^share)(UMSocialPlatformType type);
@property (nonatomic, assign) UMSAuthViewType authType;

@end

@implementation LoginViewController
#pragma mark - IBAction
- (IBAction)backAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)passwdButtonAction:(id)sender {
    [self.passwdButton setSelected:!self.passwdButton.selected];
    [self.passwd setSecureTextEntry:!self.passwdButton.selected];
}

//登录接口 ****************************************************
- (IBAction)loginBtn:(id)sender {
    if (TextIsNotNil(_phoneNum.text) && TextIsNotNil(_passwd.text)) { // [LXLIsPhoneNumber valiMobile:_phoneNum.text]
        //登录接口
        [MBProgressHUD showHUDProgress:self.view animated:YES];
//        [self startLoadingGifView];
        __weak typeof(self) weakSelf = self;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:self.phoneNum.text           forKey:@"mtel"];
        [dic setObject:self.passwd.text           forKey:@"mpass"];
        [MYAFNetworking POST:URL_Signin parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (!responseObject) {
                NSLog(@"请求失败");
                return;
            }
        
            NSDictionary *dics = responseObject;
            NSString *code = [dics safeStringForKey:@"code"];
            
            if (!(code && [code isEqualToString:@"200"])) {
                [MBProgressHUD showError:weakSelf.view title:[dics safeObjectForKey:@"message"] code:code animated:YES];
                
            } else {
                NSDictionary *data = [dics safeJsonObjectForKey:@"data"];
                
                [UserInfo shareInstance].user = [UserModel mj_objectWithKeyValues:data];
                [UserInfo shareInstance].isLogin = YES;
                [UserInfo shareInstance].isOpen = [UserInfo shareInstance].user.isopen;
                [[UserInfo shareInstance] updateUserModel];
                [[UserInfo shareInstance] connectRongCloud];
                
                [[UserInfo shareInstance] updateUserInterfaceModel:^(BOOL success) {
                    
                    [JPUSHService setAlias:[UserInfo shareInstance].user.mid completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                        NSLog(@"alias %@",iAlias);
                    } seq:[UserInfo shareInstance].user.mid.integerValue];
                    //登录跳到主页面
                    //注册成功
                    [MBProgressHUD myShowHUDAddedTo:[UIApplication sharedApplication].keyWindow labelText:@"登录成功" animated:YES];
                    [weakSelf popToRoot];
                }];
                if (weakSelf.loginSuccess) {
                    weakSelf.loginSuccess();
                }
                
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    } else {
        [self showAlertMessage:@"请输入正确的手机号和密码"];

    }
}

//跳转注册页面
- (IBAction)zhuce:(id)sender {
    
    RegisterViewController * zhuce = [[RegisterViewController alloc] init];
    zhuce.type = typeRegister;
    [self.navigationController pushViewController:zhuce animated:YES];
    
}

//跳转忘记密码页面
- (IBAction)forgetPass:(id)sender {
    RegisterViewController * forget = [[RegisterViewController alloc] init];
    forget.type = typePassword;
    [self.navigationController pushViewController:forget animated:YES];
}
/*
//  QQ    登录接口       ***********************
- (IBAction)qqLogin:(id)sender {
    
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            NSLog(@"QQ uid: %@", resp.uid);
            NSLog(@"QQ openid: %@", resp.openid);
            NSLog(@"QQ accessToken: %@", resp.accessToken);
            NSLog(@"QQ expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"QQ name: %@", resp.name);
            NSLog(@"QQ iconurl: %@", resp.iconurl);
            NSLog(@"QQ gender: %@", resp.gender);
            
            // 第三方平台SDK源数据
            NSLog(@"QQ originalResponse: %@", resp.originalResponse);
            
            __weak typeof(self) weakSelf = self;
            [MBProgressHUD showHUDProgress:self.view animated:YES];
//            [self startLoadingGifView];
            [MYAFNetworking POST:URL_Get_Member_QQ parameters:@{@"mqqid":resp.openid} success:^(NSURLSessionDataTask *task, id responseObject) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if ([responseObject[@"code"] isEqualToString:@"205"]) {
                    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
                    registerVC.thirdStr = @"qq";
                    registerVC.thirdOpenID = resp.openid;
                    registerVC.type = typeThirdQQ;
                    [self.navigationController pushViewController:registerVC animated:YES];
                } else if ([responseObject[@"code"] isEqualToString:@"200"]) {
                    NSDictionary *dics = responseObject;
                    NSString *code = [dics safeStringForKey:@"code"];
                    
                    if (!(code && [code isEqualToString:@"200"])) {
                        [MBProgressHUD showError:weakSelf.view title:[dics safeObjectForKey:@"message"] code:code animated:YES];
                        
                    } else {
                        NSDictionary *data = [dics safeJsonObjectForKey:@"data"];
                        
                        [UserInfo shareInstance].user = [UserModel mj_objectWithKeyValues:data];
                        [UserInfo shareInstance].isLogin = YES;
                        [[UserInfo shareInstance] updateUserModel];
                        [[UserInfo shareInstance] connectRongCloud];
                        
                        [[UserInfo shareInstance] updateUserInterfaceModel:^(BOOL success) {
                            //登录跳到主页面
                            //MARK:注册成功
                            [weakSelf popToRoot];
                        }];
                        if (weakSelf.loginSuccess) {
                            weakSelf.loginSuccess();
                        }
                        
                    }
                } else {
                    [MBProgressHUD showError:weakSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
            }];
            
        }
    }];
    
}

//  微信   登录接口       ***********************
- (IBAction)weixinLogin:(id)sender {
    
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            NSLog(@"Wechat uid: %@", resp.uid);
            NSLog(@"Wechat openid: %@", resp.openid);
            NSLog(@"Wechat accessToken: %@", resp.accessToken);
            NSLog(@"Wechat refreshToken: %@", resp.refreshToken);
            NSLog(@"Wechat expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"Wechat name: %@", resp.name);
            NSLog(@"Wechat iconurl: %@", resp.iconurl);
            NSLog(@"Wechat gender: %@", resp.gender);
            
            // 第三方平台SDK源数据
            NSLog(@"Wechat originalResponse: %@", resp.originalResponse);
            
            __weak typeof(self) weakSelf = self;
            [MBProgressHUD showHUDProgress:self.view animated:YES];
//            [self startLoadingGifView];
            [MYAFNetworking POST:URL_Get_Member_Wechat parameters:@{@"mwechatid":resp.openid} success:^(NSURLSessionDataTask *task, id responseObject) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
                if ([responseObject[@"code"] isEqualToString:@"205"]) {
                    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
                    registerVC.thirdStr = @"wechat";
                    registerVC.thirdOpenID = resp.openid;
                    registerVC.type = typeThirdWechat;
                    [self.navigationController pushViewController:registerVC animated:YES];
                } else if ([responseObject[@"code"] isEqualToString:@"200"]) {
                    NSDictionary *dics = responseObject;
                    NSString *code = [dics safeStringForKey:@"code"];
                    
                    if (!(code && [code isEqualToString:@"200"])) {
                        [MBProgressHUD showError:weakSelf.view title:[dics safeObjectForKey:@"message"] code:code animated:YES];
                        
                    } else {
                        NSDictionary *data = [dics safeJsonObjectForKey:@"data"];
                        
                        [UserInfo shareInstance].user = [UserModel mj_objectWithKeyValues:data];
                        [UserInfo shareInstance].isLogin = YES;
                        [[UserInfo shareInstance] updateUserModel];
                        [[UserInfo shareInstance] connectRongCloud];
                        
                        [[UserInfo shareInstance] updateUserInterfaceModel:^(BOOL success) {
                            //登录跳到主页面
                            //MARK:注册成功
                            [weakSelf popToRoot];
                        }];
                        if (weakSelf.loginSuccess) {
                            weakSelf.loginSuccess();
                        }
                        
                    }
                } else {
                    [MBProgressHUD showError:weakSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
            }];
        }
    }];
}
*/
 #pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self updateBackView];
    
    self.phoneNum.delegate = self;
    self.passwd.delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeText:)
                                                name:UITextFieldTextDidChangeNotification
                                              object:_phoneNum];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldDidChangeText:)
                                                name:UITextFieldTextDidChangeNotification
                                              object:_passwd];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
- (void)updateBackView {
//    [self.phoneNumBackView setHalfCircleWithColor:[UIColor whiteColor]];
//    [self.passWordBackView setHalfCircleWithColor:[UIColor whiteColor]];
//    [self.loginButton setHalfCircleWithColor:[UIColor whiteColor]];
    
    NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:PhoneNumber];
    if (TextIsNotNil(phone)) {
        [_phoneNum setText:phone];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@""]) {
        return YES;
    }
    
    if ([string isEqualToString:@" "]) {
        return NO;
    }
    if (textField.tag == 1000) {
        if (textField.text.length >= 11) {
            return NO;
        }else{
            return YES;
        }
    } else if (textField.tag == 1001){
        
        //判断是否是数字，不是的话就输入失败
        
//        NSCharacterSet *cs;
//        cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
        
        
        
        // 6~16位 字母+数字
        if (textField.text.length >= 16 || [string isNumAndChar] == NO) {
            return NO;
        } else {
            return YES;
        }
    } else
        return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidChangeText:(NSNotification *)info {
    if (TextIsNotNil(self.phoneNum.text) && TextIsNotNil(self.passwd.text)) {
        [self.loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.loginButton setBackgroundColor:[UIColor ThemeColor]];
        [self.loginButton setUserInteractionEnabled:YES];
    } else {
        [self.loginButton setTitleColor:[UIColor grayTextColor] forState:UIControlStateNormal];
        [self.loginButton setBackgroundColor:[UIColor grayDDColor]];
        [self.loginButton setUserInteractionEnabled:NO];
    }
}
#pragma mark -
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UITextFieldTextDidChangeNotification
                                                 object:_phoneNum];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:UITextFieldTextDidChangeNotification
                                                 object:_passwd];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
